<template>
  <view class="container">
    <view class="boxPanel flex-between">
      <view class="text-bold flex-y-center">
        联系人
        <text class="font-24 c-89">（必填项）</text>
      </view>
      <input
        type="text"
        placeholder="请输入联系人"
        v-model="name"
        placeholder-class="inputs"
        class="text-right"
        style="width: 50%"
      />
    </view>

    <view class="boxPanel flex-between">
      <view class="text-bold flex-y-center"
        >联系电话
        <text class="font-24 c-89">（必填项）</text>
      </view>
      <input
        type="number"
        maxlength="11"
        placeholder="请输入联系电话"
        v-model="mobile"
        placeholder-class="inputs"
        class="text-right"
        style="width: 50%"
      />
    </view>

    <view class="boxPanel flex-between" @click="openTimePicker" v-if="!moduleType">
      <view class="text-bold">预约时间</view>
      <view class="flex-y-center" style="width: 58%; justify-content: flex-end">
        <input
          type="text"
          disabled
          placeholder="请选择时间"
          v-model="subscribe_time"
          placeholder-class="inputs"
          class="text-right"
          style="width: 100%"
        />
        <u-icon name="arrow-right" color="#788096" size="14"></u-icon>
      </view>
    </view>

    <view class="boxPanel flex-between" v-if="!moduleType">
      <view class="text-bold flex-y-center">
        购买数量
        <text class="color-title2" v-if="maxBuy > 0">(限购{{ maxBuy }})</text>
      </view>
      <view class="flex-y-center" style="width: 58%; justify-content: flex-end" v-if="maxBuy > 0">
        <u-number-box v-model="goods_num" @change="valChange" :max="maxBuy"></u-number-box>
      </view>
      <view class="flex-y-center" style="width: 58%; justify-content: flex-end" v-else>
        <u-number-box v-model="goods_num" @change="valChange"></u-number-box>
      </view>
    </view>

    <view class="boxPanel flex-between" v-if="moduleType == 'social'">
      <view class="text-bold">报名人数</view>
      <view class="flex-y-center" style="width: 50%">
        <input
          type="number"
          maxlength="2"
          placeholder="请填写人数"
          v-model="people_num"
          placeholder-class="inputs"
          class="text-right"
        />
      </view>
    </view>

    <view class="boxPanel flex-x-between" @click="chooseAddress()" v-if="!moduleType">
      <view class="text-bold">服务地址</view>
      <view class="flex-y-center" style="width: 50%">
        <input
          type="text"
          placeholder="请选择地址"
          v-model="address"
          disabled
          placeholder-class="inputs"
          class="text-right"
          v-if="!address"
        />
        <view class="inputs" style="line-height: 1.4; color: #172140" v-else>{{ address }}</view>
        <u-icon name="arrow-right" color="#788096" size="14"></u-icon>
      </view>
    </view>

    <view class="flex-x-between boxPanel" v-if="orderPaymentData.shop_goods_list.coupon_list.length">
      <view class="text-bold">优惠券</view>
      <view class="flex-y-center" @click="openCoupon()">
        <view class="box text-overflow">
          <template v-if="orderPaymentData.coupon.coupon_id">
            <text class="c-5d">已使用优惠券，优惠</text>
            <text class="color-title2 unit">￥</text>
            <text class="color-title2 money">{{ orderPaymentData.coupon_money | moneyFormat }}</text>
          </template>
          <text class="c-5d" v-else>不使用优惠券</text>
        </view>
        <u-icon name="arrow-right" size="18" color="#B8BAC2"></u-icon>
      </view>
    </view>

    <view class="boxPanel flex-between">
      <view class="text-bold flex-y-center"> 备注 </view>
      <input
        type="text"
        placeholder="请填写备注"
        v-model="remark"
        placeholder-class="inputs"
        class="text-right"
        style="width: 50%"
      />
    </view>

    <view class="boxPanel" v-if="parseFloat(price) > 0">
      <view class="font-30 text-bold m-b-20"> 支付方式 </view>
      <view class="payrow" v-for="(item, index) in paylist" :key="index" @click="changePayment(index)">
        <image :src="$util.img(item.icon)" mode="" class="payimg"></image>
        {{ item.name }}
        <text class="color-title2 m-l-20" v-if="item.name == '余额支付'"
          >可用¥{{
            orderPaymentData.order_money > 0 && orderPaymentData.member_account.balance_total > 0 ? balanceDeduct : "0"
          }}</text
        >
        <image :src="$util.img('image/radio2.png')" mode="" class="radio" v-if="payIndex == index"></image>
        <image :src="$util.img('image/radio.png')" mode="" class="radio" v-else></image>
      </view>
    </view>

    <view style="height: 120rpx"></view>
    <view class="footer fixfooter" v-if="parseFloat(price) == 0">
      <view class="submit" @click="submit">{{ !pageType ? "立即预约" : "立即购买" }}</view>
    </view>

    <view class="footer2 fixfooter" v-else>
      <view class="">
        <view class="font-24 c-8d">共 1 件 需支付</view>
        <view class="money c-origin text-bold font-52 flex" style="align-items: baseline; margin-top: -16rpx">
          <text class="font-28 c-origin">￥</text>{{ pay_money | moneyFormat }}
        </view>
      </view>
      <view class="submit" @click="submit">立即支付</view>
    </view>
    <!-- 引入时间组件 -->
    <choose-time
      ref="chooseTime"
      :show="showTime"
      @close="showTime = false"
      @chooseTime="chooseTime"
      @reset="reset"
    ></choose-time>
    <!-- 选择优惠券组件 -->
    <chooseCoupon
      :show="showCoupon"
      @close="showCoupon = false"
      v-if="showCoupon"
      :couponList="orderPaymentData.shop_goods_list.coupon_list"
      :couponId="orderPaymentData.coupon.coupon_id"
      @popupConfirm="popupConfirm"
      @selectCoupon="selectCoupon"
    ></chooseCoupon>
    <!-- 引入校验服务范围组件 -->
    <locationScope :show="showLocationScope" @close="closeLocationScope" v-if="showLocationScope"></locationScope>
  </view>
</template>

<script>
import chooseCoupon from "../../components/chooseCoupon/chooseCoupon.vue";
import chooseTime from "components/chooseTime/chooseTime.vue";
export default {
  components: {
    chooseTime,
    chooseCoupon,
  },
  data() {
    return {
      name: "",
      mobile: "",
      subscribe_time: "",
      address: "",

      isSubmitting: false,
      defaultList: [],
      //日历数据
      showCalendar: false,
      round: 10,
      date: "",
      // 时分数据
      showTime: false,
      value1: "00:00",
      remark: "",
      people_num: "",
      minDate: "",
      // 支付参数
      paylist: [
        {
          name: "微信支付",
          icon: "/image/pay2.png",
        },
        {
          name: "余额支付",
          icon: "/image/pay1.png",
        },
      ],
      payIndex: 0,
      balance: 0, //余额
      is_balance: 0, //是否余额支付
      goods_num: 1, //商品数量

      price: 0,
      goodsid: 0,
      pageType: "",
      moduleType: "", //模块类型social 文娱社交
      backUrl: "/otherpages/serviceSign/serviceSign",
      memberPrice: 0,
      originPrice: 0, //原始价格数据，不被污染
      coupon: {},
      orderCreateData: {
        is_balance: 0,
      },
      orderPaymentData: {
        shop_goods_list: {
          coupon_list: [],
        },
        member_account: {
          balance: 0,
        },
        coupon_money: 0,
      },
      //优惠券部分
      showCoupon: false,
      pay_money: 0, //实际支付金额
      pay_balance_money: 0, //余额支付时实际支付金额
      addressInfo: {},
      // 服务范围
      showLocationScope: false,
      locationScope: false,
      maxBuy: 0, //限购数量
    };
  },
  filters: {
    // 金额格式化输出
    moneyFormat(money) {
      return parseFloat(money).toFixed(2);
    },
  },
  computed: {
    // 余额抵扣
    balanceDeduct() {
      if (
        this.orderPaymentData.member_account.balance_total <= parseFloat(this.orderPaymentData.order_money).toFixed(2)
      ) {
        return parseFloat(this.orderPaymentData.member_account.balance_total).toFixed(2);
      } else {
        return parseFloat(this.orderPaymentData.member_account.balance_total).toFixed(2);
      }
    },
  },
  onLoad(data) {
    if (data.params) {
      let params = JSON.parse(data.params);
      if (params.pageType) this.pageType = params.pageType;
      if (params.moduleType) this.moduleType = params.moduleType;
      if (params.price) this.price = params.price;
      if (params.goodsid) this.goodsid = params.goodsid;
      if (params.memberPrice) {
        this.memberPrice = params.memberPrice;
        this.originPrice = params.memberPrice;
      }

      // if(!this.pageType) {
      // 	uni.setNavigationBarTitle({
      // 		title: '预约活动'
      // 	})
      // }
    }
    if (uni.getStorageSync("subscribe_order")) {
      var data = uni.getStorageSync("subscribe_order");
      this.name = data.subscribe_name;
      this.mobile = data.subscribe_mobile;
      this.address = data.subscribe_address;
      this.subscribe_time = data.subscribe_time;
    } else {
      // 获取缓存的用户信息，将昵称赋值给姓名，手机号赋值
      var userInfo = uni.getStorageSync("userInfo");
      if (userInfo) {
        this.name = userInfo.nickname;
        this.mobile = userInfo.mobile;
      }
    }
    // if (uni.getStorageSync("userInfo")) {
    //   this.balance = uni.getStorageSync("userInfo").balance;
    // }
  },
  onShow() {
    this.getDefaultAddress();
    this.getOrderPaymentData();
  },
  methods: {
    checkedLocationScope() {
      this.$api.sendRequest({
        url: "/api/subscribeordercreate/verifyGoodsArea",
        data: {
          latitude: this.addressInfo.latitude,
          longitude: this.addressInfo.longitude,
          goods_id: this.goodsid,
        },
        success: (res) => {
          if (res.code == 0) {
            this.showLocationScope = false;
            this.locationScope = false;
          } else {
            this.showLocationScope = true;
            this.locationScope = true;
          }
        },
      });
    },
    closeLocationScope() {
      this.showLocationScope = false;
    },
    popupConfirm() {
      this.orderCalculate();
      this.$forceUpdate();
      this.showCoupon = false;
    },
    // 选择优惠券
    selectCoupon(item) {
      if (this.orderCreateData.coupon.coupon_id != item.coupon_id) {
        this.orderCreateData.coupon.coupon_id = item.coupon_id;
        this.orderCreateData.coupon.coupon_money = item.money;
      } else {
        this.orderCreateData.coupon.coupon_id = 0;
        this.orderCreateData.coupon.coupon_money = "0.00";
      }
      Object.assign(this.orderPaymentData, this.orderCreateData);
      this.$forceUpdate();
    },
    openCoupon() {
      this.showCoupon = true;
    },
    getOrderPaymentData() {
      this.$api.sendRequest({
        url: "/api/subscribeordercreate/payment",
        method: "POST",
        data: {
          goods_id: this.goodsid,
          is_balance: this.orderCreateData.is_balance,
        },
        success: (res) => {
          if (res.code == 0) {
            this.orderPaymentData = res.data;
            this.handlePaymentData();
          } else {
            this.$util.showToast({
              title: res.message,
            });
          }
        },
      });
    },
    handlePaymentData() {
      this.orderCreateData.coupon = {};
      this.orderCreateData.is_balance = 0;

      var data = this.orderPaymentData;

      // 处理限购-新增2025-11-20 流年
      if (data.shop_goods_list.goods_list[0].is_limit == 1) {
        this.maxBuy = data.shop_goods_list.goods_list[0].max_buy;
      }

      // 店铺优惠券
      if (data.shop_goods_list.coupon_list != undefined && data.shop_goods_list.coupon_list[0] != undefined) {
        var coupon_list = data.shop_goods_list.coupon_list;
        this.orderCreateData.coupon.coupon_id = coupon_list[0].coupon_id;
        this.orderCreateData.coupon.coupon_money = coupon_list[0].money;
      }
      Object.assign(this.orderPaymentData, this.orderCreateData);
      this.orderCalculate();
    },
    // 订单计算
    orderCalculate() {
      var data = this.$util.deepClone(this.orderCreateData);
      data.coupon = JSON.stringify(data.coupon);

      var data = {
        goods_id: this.goodsid,
        is_balance: this.orderCreateData.is_balance,
        goods_num: this.goods_num,
        coupon: data.coupon,
      };
      // 判断是否使用购物卡支付进行计算，如果是则传递is_shoppingcard参数为1
      //   if (this.payIndex == 0) {
      //     data.is_shoppingcard = 1;
      //   }

      this.$api.sendRequest({
        url: "/api/subscribeordercreate/calculate",
        data: data,
        success: (res) => {
          if (res.code >= 0) {
            this.orderPaymentData.coupon_money = res.data.coupon_money;
            this.orderPaymentData.order_money = res.data.order_money;
            this.orderPaymentData.balance_money = res.data.balance_money;
            this.orderPaymentData.pay_money = res.data.pay_money;
            this.orderPaymentData.goods_money = res.data.goods_money;
            this.orderPaymentData.shop_goods_list.goods_list = res.data.shop_goods_list.goods_list;
            this.orderPaymentData.coupon_money = res.data.coupon_money;

            this.pay_money = res.data.order_money;
            this.pay_balance_money = res.data.pay_money;

            // 针对优惠券特殊处理
            if (this.orderPaymentData.shop_goods_list.coupon_list.length == 0) {
              this.orderCreateData.coupon = {};
            }

            this.$forceUpdate();
          } else {
            this.$util.showToast({
              title: res.message,
            });
          }
        },
      });
    },
    valChange(e) {
      // console.log("1111", e);
      // 数量变化，总金额进行累计
      let num = e.value;
      this.memberPrice = (parseFloat(this.originPrice) * num).toFixed(2);
      this.goods_num = num;
      this.orderCalculate();
    },
    reset(e) {
      this.subscribe_time = "";
      this.showTime = false;
    },
    chooseTime(e) {
      this.subscribe_time = e.time_day;
      this.showTime = false;
    },
    changePayment(index) {
      if (index == 1) {
        // 比对余额是否满足支付金额
        // 比对余额是否满足支付金额
        if (parseFloat(this.orderPaymentData.member_account.balance) < parseFloat(this.orderPaymentData.pay_money)) {
          uni.showToast({
            title: "余额不足，请选择其他支付方式",
            icon: "none",
          });
          return;
        } else {
          this.orderCreateData.is_balance = 1;
          this.payIndex = index;
        }
      } else {
        this.orderCreateData.is_balance = 0;
        this.payIndex = index;
      }
      this.orderCalculate();
      this.$forceUpdate();
    },
    chooseAddress() {
      this.$util.redirectTo("/pages/address/address", { back: this.backUrl });
    },
    openTimePicker() {
      this.showTime = true;
    },
    formatter(type, value) {
      if (type === "hour") {
        return `${value}时`;
      }
      if (type === "minute") {
        return `${value}分`;
      }
      return value;
    },
    confirmTime(e) {
      console.log(e);
      let selectedTimeStr = this.date + " " + e.value + ":00";

      // 将选择的时间转换为时间戳
      let selectedTime = new Date(selectedTimeStr).getTime();
      // 获取当前时间往后推迟一个小时的时间戳
      let minTime = new Date().getTime() + 3600 * 1000;

      // 判断选择的时间是否小于最小允许时间
      if (selectedTime < minTime) {
        uni.showToast({
          title: "预约时间必须至少在当前时间1小时后",
          icon: "none",
        });
        return false;
      }

      this.showTime = false;
      this.subscribe_time = this.date + " " + e.value;
    },
    confirmCalendar(e) {
      console.log(e);
      this.date = e[0];
      this.showCalendar = false;
      this.showTime = true;
    },
    getDefaultAddress() {
      this.$api.sendRequest({
        url: "/api/memberaddress/page",
        data: {
          page: 1,
          page_size: 30,
        },
        success: (res) => {
          if (res.code == 0) {
            var arr = res.data.list;
            var newDefault = [];
            arr.forEach((v, k) => {
              if (v.is_default == 1) {
                newDefault.push(v);
                arr.splice(k, 1);
              }
            });
            let defaultList = newDefault;
            this.address = defaultList[0].full_address + defaultList[0].address;
            this.addressInfo = defaultList[0];
            if (defaultList.length > 0 && !this.moduleType) {
              this.checkedLocationScope();
            }
          }
        },
      });
    },

    submit() {
      if (this.locationScope && !this.moduleType) {
        uni.showToast({
          title: "您当前地址已经超出我们的服务范围，请重新选择服务地址",
          icon: "none",
        });
        return;
      }
      if (!this.name) {
        uni.showToast({
          title: "请输入姓名",
          icon: "none",
        });
        return false;
      }
      if (!this.mobile || this.mobile.length != 11) {
        uni.showToast({
          title: "请输入手机号",
          icon: "none",
        });
        return false;
      }

      // 增加时间校验逻辑
      if (!this.moduleType && this.subscribe_time) {
        // 第一种时间格式如: 2025-08-26 10:00进行的比较形式
        // let selectedTimeStr = this.subscribe_time + ':00'

        // // 将选择的时间转换为时间戳
        // let selectedTime = new Date(selectedTimeStr).getTime()
        // // 获取当前时间往后推迟一个小时的时间戳
        // let minTime = new Date().getTime() + 3600 * 1000

        // 判断选择的时间是否小于最小允许时间
        // if (selectedTime < minTime) {
        // 	uni.showToast({
        // 	title: '预约时间必须至少在当前时间1小时后',
        // 	icon: 'none'
        // 	})
        // 	return false
        // }

        // 第二种时间格式如: 2025-08-26 10:00-12:00进行的比较形式
        // 解析预约时间段
        const datePart = this.subscribe_time.split(" ")[0];
        const timePart = this.subscribe_time.split(" ")[1].split("-")[0];
        const appointmentTimeStr = `${datePart} ${timePart}:00`;

        const appointmentTime = new Date(appointmentTimeStr).getTime();
        const minTime = new Date().getTime() + 3600 * 1000;

        // console.log(datePart, timePart,appointmentTimeStr,appointmentTime);

        if (appointmentTime < minTime) {
          uni.showToast({
            title: "预约时间必须至少在当前时间1小时后",
            icon: "none",
          });
          return false;
        }
      }

      if (this.isSubmitting) return false;
      this.isSubmitting = true;

      var data = this.$util.deepClone(this.orderCreateData);
      data.coupon = JSON.stringify(data.coupon);

      this.$api.sendRequest({
        url: "/api/subscribeordercreate/create",
        data: {
          goods_id: this.goodsid,
          name: this.name,
          mobile: this.mobile,
          subscribe_time: this.subscribe_time,
          address: this.address,
          remark: this.remark,
          people_num: this.people_num,
          is_balance: this.orderCreateData.is_balance,
          goods_num: this.goods_num,
          coupon: data.coupon,
        },
        success: (res) => {
          // 将数据存入缓存中
          uni.setStorageSync("subscribe_order", {
            subscribe_time: this.subscribe_time,
            subscribe_address: this.address,
            subscribe_name: this.name,
            subscribe_mobile: this.mobile,
          });
          if (res.code == 0) {
            if (parseFloat(this.price) == 0 || this.orderPaymentData.pay_money == 0) {
              uni.showToast({
                title: "预约成功",
                icon: "none",
              });
              setTimeout(() => {
                uni.reLaunch({
                  url: "/otherpages/yuOrder/yuOrderList",
                });
              }, 1500);
            } else {
              this.pay(res.data);
            }
          } else {
            this.$util.showToast(res.message);
          }
        },
      });
    },
    pay(out_trade_no) {
      this.$api.sendRequest({
        url: "/api/pay/pay",
        data: {
          out_trade_no: out_trade_no,
          pay_type: "wechatpay",
        },
        success: (res) => {
          if (res.code >= 0) {
            var payData = res.data.data;
            uni.requestPayment({
              provider: "wxpay",
              timeStamp: payData.timeStamp,
              nonceStr: payData.nonceStr,
              package: payData.package,
              signType: payData.signType,
              paySign: payData.paySign,
              success: (res) => {
                this.$util.showToast({ title: "支付成功" });
                // 重新加载用户信息接口，更新用户信息数据
                this.getMemberInfo();
                uni.reLaunch({
                  url: "/otherpages/yuOrder/yuOrderList",
                });
              },
              fail: (res) => {
                this.flag = false;
                uni.reLaunch({
                  url: "/otherpages/yuOrder/yuOrderList",
                });
                if (res.errMsg == "requestPayment:fail cancel") {
                  this.$util.showToast({ title: "您已取消支付" });
                } else {
                  uni.showModal({ content: "支付失败,失败原因: " + res.errMsg, showCancel: false });
                }
              },
            });
          } else {
            this.$util.showToast({
              title: "未获取到支付信息！",
            });
          }
        },
      });
    },
    getMemberInfo() {
      this.$api.sendRequest({
        url: "/api/member/info",
        data: {},
        success: (res) => {
          if (res.code >= 0 && res.data) {
            uni.setStorageSync("userInfo", res.data);
          }
        },
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.boxPanel {
  .inputs {
    font-size: 28rpx;
    color: #b5b9c7;
  }
  .txt {
    font-size: 32rpx;
    font-weight: bold;
  }
}
// 支付方式选项
.payrow {
  display: flex;
  align-items: center;
  padding: 16rpx 0;
  font-size: 26rpx;
  width: 100%;
  .payimg {
    width: 67rpx;
    height: 67rpx;
    margin-right: 20rpx;
  }
  .radio {
    width: 34rpx;
    height: 34rpx;
    margin-left: auto;
  }
}

.footer2 {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 24rpx;
  box-sizing: border-box;
  .submit {
    width: 265rpx;
    height: 86rpx;
    line-height: 86rpx;
    text-align: center;
    background-color: $color-title2;
    color: #fff;
    border-radius: 40rpx;
  }
}
</style>
